# -*- coding: utf-8 -*-
from django import forms
from django.core.paginator import Paginator, InvalidPage, EmptyPage

from google.appengine.ext.db import djangoforms
from google.appengine.ext import db

from mobile.models import MyLocation
from mobile.decorators import render_to

import logging

@render_to('mobile/mylocation/google_map.html')
def location(request):
    return {}

class MyLocationForm(djangoforms.ModelForm):
    class Meta:
        model = MyLocation
        exclude = ('id', 'date',)

@render_to('mobile/mylocation/add.html')
def add(request):
    data = request.POST.copy()
    latitude = data.get('latitude', 0)
    longitude = data.get('longitude', 0)
    comment = data.get('comment', '')
    if latitude and longitude:
        my_location = MyLocation()
        my_location.geoPoint = db.GeoPt(float(latitude), float(longitude))
        my_location.comment = comment
        my_location.put()
    return {}


@render_to('mobile/mylocation/list.html')
def list(request):
    PAGESIZE = 1
    next = None
#    my_locations = MyLocation.all().order("-date").fetch(1001)
    query = MyLocation.gql('ORDER BY date ASC')
    my_locations = query.fetch(1000)

#    if len(my_locations) == PAGESIZE + 1:
#        next = my_locations[-1].id
#    my_locations = my_locations[:PAGESIZE]
#    return {
#        'my_locations': my_locations,
#        'next': next,
#    }


#    def get_objects_page_context(objects, arguments, search_form=None):
#    if 'order' in arguments:
#        objects = objects.order_by(arguments['order'])
#    if search_form:
#        objects = search_form.search(objects)
#    number_of_records = 0
#    if objects:
#        if isinstance(objects, QuerySet):
#            number_of_records = objects.count()
#        else:
#            number_of_records = len(objects)

    paginator = Paginator(my_locations, 1)
    try:
        page_num = int(request.GET.get('page', '1'))
    except ValueError:
        page_num = 1
    try:
        objects_page = paginator.page(page_num)
    except (EmptyPage, InvalidPage):
        objects_page = paginator.page(paginator.num_pages)

    adjacent_pages = 2
    page_numbers = [n for n in \
                    range(page_num - adjacent_pages, page_num + adjacent_pages + 1) \
                    if n > 0 and n <=paginator.num_pages]
    return {
        'page_num': page_num,
        'objects_page': objects_page,
#        'number_of_records': number_of_records,
#        'url_arguments': URLArgument(arguments),
#        'search_form': search_form,

#        'page_numbers': page_numbers,
        'next': objects_page.next_page_number(),
        'previous': objects_page.previous_page_number(),
        'has_next': objects_page.has_next(),
        'has_previous': objects_page.has_previous,
#        'show_first': 1 not in page_numbers,
#        'show_last': paginator.num_pages not in page_numbers,
#        'last_page': paginator.num_pages,
        }